#include <iostream>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#define PAGE_SIZE 4096

// write_map filename
int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        std::cout << "Usage: " << argv[0] << " filename" << std::endl;
        return 1;
    }

    // 1.打开目标文件，mmap不会帮忙打开
    int fd = open(argv[1], O_RDWR | O_CREAT | O_TRUNC, 0666);
    if (fd < 0)
    {
        std::cout << "Failed to open file: " << argv[1] << std::endl;
        return 2;
    }

    if (::ftruncate(fd, PAGE_SIZE) == -1)
    {
        std::cout << "Failed to truncate file: " << argv[1] << std::endl;
        return 3;
    }

    char* shmaddr = (char*)::mmap(NULL, PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (shmaddr == MAP_FAILED)
    {
        std::cout << "Failed to mmap file: " << argv[1] << std::endl;
        return 4;
    }

    for (char c = 'a' ; c <= 'z' ; c++)
    {
        shmaddr[c - 'a'] = c;
        sleep(1);
    }


    if (::munmap(shmaddr, PAGE_SIZE) == -1)
    {
        std::cout << "Failed to munmap file: " << argv[1] << std::endl;
        return 5;
    }

    close(fd);


    return 0;
}